﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TimeSnapperPluginAPI;
using System.Diagnostics;

namespace SqlExecuterPlugin
{
    public partial class QueryForm : Form
    {
        private IServices m_services;
        private const string cLastQuery = "SqlExecuterPlugin.LastQuery";

        public QueryForm(IServices services)
        {
            InitializeComponent();

            m_services = services;
            grd.AutoGenerateColumns = true;
            txtQuery.Text = m_services.SettingsServices.GetPropertyValue(cLastQuery, "select * from options");
        }

        private void QueryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_services.SettingsServices.SetPropertyValue(cLastQuery, txtQuery.Text);
        }

        private void executeSQLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExecuteSql();
        }

        private void ExecuteSql()
        {
            DataTable dt;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string sql;
                if (txtQuery.SelectionLength > 0)
                {
                    // the user has selected a portion of the text -- only execute that
                    sql = txtQuery.SelectedText;
                }
                else
                {
                    // execute everything found in the textbox
                    sql = txtQuery.Text;
                }
                dt = m_services.DatabaseServices.ExecuteQuery(sql, "table1");
                TabControl1.SelectedTab = TabPage1;
                grd.DataSource = dt;
                grd.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
                txtResult.Text = "";
                txtQuery.Focus();
            }
            catch (Exception ex)
            {
                ShowUserError(ex.Message);
                txtQuery.Focus();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void QueryForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F5)
                ExecuteSql();
        }

        private void availableTablesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string sql;
            sql = @"select rdb$relation_name
from rdb$relations
where rdb$view_blr is null 
and (rdb$system_flag is null or rdb$system_flag = 0)
order by 1";
            txtResult.Text = sql;
            TabControl1.SelectedTab = TabPage2;
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void databaseModelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string url = "http://wiki.timesnapper.com/index.php?title=Database_Model";
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.UseShellExecute = true;
                psi.FileName = url;
                Process.Start(psi);
            }
            catch (Exception ex)
            {
                ShowUserError("Unable to start your default web browser.  Manually navigate to:" + System.Environment.NewLine +
                    url + System.Environment.NewLine + System.Environment.NewLine +
                    "(Error: " + ex.Message + ")");
            }
        }

        private void ShowUserError(string msg)
        {
            txtResult.Text = msg;
            txtResult.SelectionLength = 0;
            TabControl1.SelectedTab = TabPage2;
        }
    }
}
